import React, { useState, useEffect } from 'react'
import NavBarAgain from "../components/NavBarAgain"
import { Form, Input, Toast } from 'antd-mobile'
import "./Login.less"
import { sendPhoneCode, login } from "../api"
import ButtonAgain from "../components/ButtonAgain"
import _ from "../assets/utils"
import { connect } from 'react-redux';
import action from "../store/action"



const validate = {
    phone(_, value) {
        value = value.trim();
        if (!value) return Promise.reject("手机号是必填项");
        let reg = /^(?:(?:\+|00)86)?1\d{10}$/;
        if (!reg.test(value)) return Promise.reject("手机号格式有误")
        return Promise.resolve()
    },
    code(_, value) {
        value = value.trim();
        let reg = /^\d{6}$/;
        if (value.length === 0) return Promise.reject(new Error('验证码是必填项!'));
        if (!reg.test(value)) return Promise.reject(new Error('验证码格式有误!'));
        return Promise.resolve();
    }
}

const Login = function Login(props) {
    const [form] = Form.useForm();
    let [text, setText] = useState("发送验证码");
    let [isDisabled, setDisabled] = useState(false);

    let timer;
    const setTime = () => {
        let sum = 10;
        timer = setInterval(() => {
            if (sum > 0) {
                setText(`${sum--}秒后重发`);
                return;
            };
            clearInterval(timer);
            timer = null;
            setText("发送验证码");
            setDisabled(false);
        }, 1000)
    }

    const submit = async () => {
        try {
            await form.validateFields();
            let { phone, code } = form.getFieldsValue()
            let { code: submitCode, token } = await login(phone, code);
            if (submitCode) {
                Toast.show({ icon: "fail", content: "验证码错误" });
                form.resetFields(["code"])
            };
            _.storage.set("tk", token);
            await props.queryUserInfoAsync();
            Toast.show({ icon: "success", content: "成功" });
            if (props.search.get("to")) {
                props.navigate(props.search.get("to"), { replace: true })
            } else {
                props.navigate(-1)
            }
        } catch (error) {
        }

    }

    const send = async () => {
        try {
            await form.validateFields(["phone"]);
            let phone = form.getFieldValue("phone");
            let res = await sendPhoneCode(phone);
            if (res.code) {
                Toast.show({ icon: "fail", content: "发送失败" });
                return;
            };
            setDisabled(true);
            Toast.show({ icon: "success", content: "发送成功" });
            setTime()
        } catch (error) {
        }
    }

    useEffect(() => {
        return () => {
            if (timer) {
                clearInterval(timer);
                timer = null
            }
        }
    }, [])

    return (
        <div className='login-box'>
            <NavBarAgain title="登录/注册"></NavBarAgain>
            <Form layout='horizontal' form={form} style={{ "--border-top": "none" }}
                initialValues={{ phone: "", code: "" }}
                footer={
                    <ButtonAgain color='primary' fn={submit}>
                        提交
                    </ButtonAgain>}
            >
                <Form.Item name='phone' label='手机号' rules={[{ validator: validate.phone }]}>
                    <Input placeholder='请输入手机号' />
                </Form.Item>

                <Form.Item name='code' label='验证码' rules={[{ validator: validate.code }]}
                    extra={
                        <ButtonAgain size='mini' color='primary' disabled={isDisabled} fn={send}>{text}</ButtonAgain>
                    }>
                    <Input placeholder='请输入验证码' />
                </Form.Item>
            </Form>
        </div>
    )
}

export default connect(null, action.base)(Login)